<?php

/**
 * VIPSHOP Db
 *
 * @category Vipcore
 * @package Vipcore_Db
 * @author xc
 */
namespace library\Core\Db;

use library\Core\Exception\DbException;
use library\Core\Db\CDbConnection;

class CDbFactory {
	
	protected static $_instance = array();
	
	/**
	 * db工厂方法
	 *
	 * @param $dbName string
	 * @param $adapter string
	 * @return 
	 */
	static public function factory($dbName, $adapter = 'master') {	
	    
	    if (isset(self::$_instance[$dbName][$adapter])) {
	        return self::$_instance[$dbName][$adapter];
	    }
	    
	    
	    $dbConfig = \library\Core\Config::getDbConfig($dbName);
	    
        if(empty($dbConfig)){
            throw new DbException('db config not set properly');
        }
        
        if(!isset($dbConfig[$adapter]) || empty($dbConfig[$adapter])){
            throw new DbException('db adapter config not set properly');
        }
        
        $config = $dbConfig[$adapter];
        if($adapter === 'slave'){
            $k = array_rand($dbConfig[$adapter]);
            $config = $dbConfig[$adapter][$k];
        }
        
        self::$_instance[$dbName][$adapter] = new CDbConnection($config);
        
        return self::$_instance[$dbName][$adapter];
	}
	


}

